#include "Configurator.h"

Configurator::Configurator(int argc, char** argv)
{
    settings = new Settings();
	settings -> GetSettings(argc, argv);
}

void Configurator :: WriteSettings()
{
    char* stringSettings = settings -> StringSettings();
	printf(stringSettings);
	fopen_s(&profile, settings -> profileFile, "wb");
    fprintf(profile, stringSettings);
}

void Configurator :: GetContent(char **mainContent, int *contentSize, char **patternContent, int *stateDimensionCoincidence)
{
	FILE *file;	
	int size = 0;
	fopen_s(&file, settings -> inputFile, "rb");			// Opening the input file
	int currentChar = getc(file);
	while (currentChar != 1)								// while the current symbol is not equal to delimeter ((char)'1') read the pattern
    {
		currentChar = getc(file);
		size++;
    }

	*stateDimensionCoincidence = size;
	rewind (file);											// reposition the file pointer to the file beginning
	*patternContent = (char*) malloc (sizeof(char)*(*stateDimensionCoincidence));	// dynamic memory memory allocation for pattern
	fread (*patternContent, sizeof(char), *stateDimensionCoincidence, file);		// read the pattern content to char array
	
	fseek (file, 0 , SEEK_END);								// move the file pointer on the end of content file		
	*contentSize = ftell (file) - size;		     		    // size of string	

	rewind (file);											// reposition the file pointer to the file beginning

	currentChar = getc(file);								// set position to the delimeter
	while (currentChar != 1)								// while the current symbol is not equal to delimeter ((char)'1') read the pattern
    {
		currentChar = getc(file);
    }
	*mainContent = (char*) malloc (sizeof(char)*(*contentSize));	// dynamic memory memory allocation for [contentSize] char array
	fread (*mainContent, sizeof(char), *contentSize, file);			// read the file content to char array
	
	fclose(file);
}

void Configurator :: Close(double time, list<int> positions)
{
	printf("Clock time   (sec): %.8f \r\n", time); 
	fprintf(profile, "Clock time   (sec): %.8f \r\n", time); 
	FILE *result;	
	fopen_s(&result, settings -> resultFile, "wb");

	if (! positions.empty())
	{
		while(! positions.empty()){		// write all the positions values
			fprintf(result, "Position: %i\r\n", positions.front());
			positions.pop_front();		// traverse the list: print the front and delete.
		}
	}
	else	
	{
		fprintf(result, "%s\r", "Pattern not found");
	}
	fclose(result);
	fclose(profile);
}